import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '../store'
/* 
封装一个函数，用来检测你是否含有当前地址的访问权
*/
function hasUrl(path,next){
  // let result = JSON.parse(sessionStorage.getItem('userinfo')).menus_url.find(item=>{
  //   return item==path
  // });
  let result = store.state.userinfo.menus_url.find(item=>item==path);
  if(result){
    next()
  }else{
    next('/home')
  }

}
Vue.use(VueRouter)

export const indexRoutes = [
  {
    path:'/menu',
    component:()=>import('../views/menu/menu'),
    meta:{
      title:'菜单管理'
    },
    beforeEnter: (to, from, next) => {
      hasUrl('/menu',next)
    }
  },
  {
    path:'/role',
    component:()=>import('../views/role/role'),
    meta:{
      title:'角色管理'
    },
    beforeEnter: (to, from, next) => {
      hasUrl('/role',next)
    }
  },
  {
    path:'/manger',
    component:()=>import('../views/manger/manger'),
    meta:{
      title:'管理员管理'
    },
    beforeEnter: (to, from, next) => {
      hasUrl('/manger',next)
    }
  },
  {
    path:'/cate',
    component:()=>import('../views/goodscate/goodscate'),
    meta:{
      title:'商品分类'
    },
  },
  {
    path:'/specs',
    component:()=>import('../views/specs/specs.vue'),
    meta:{
      title:'商品规格'
    },
  },
  {
    path:'/goods',
    component:()=>import('../views/goods/goods.vue'),
    meta:{
      title:'商品管理'
    },
  },
  {
    path:'/member',
    component:()=>import('../views/member/member.vue'),
    meta:{
      title:'会员管理'
    },
  },
  {
    path:'/banner',
    component:()=>import('../views/banner/banner.vue'),
    meta:{
      title:'轮播图管理'
    },
  },
  {
    path:'/seck',
    component:()=>import('../views/seck/seck.vue'),
    meta:{
      title:'秒杀管理'
    },
  },
]

const routes = [
  {
    path: '/login',
    component: () => import('../pages/login')
  },
  {
    path: '/index',
    component: () => import('../pages/index'),
    children: [
      {
        path:'/home',
        component:()=>import('../views/home')
      },
      ...indexRoutes,
      {
        path:'',
        redirect:'/home'
      }
    ]
  },
  {
    path: '*',
    redirect: '/index'
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

//封装一个登录拦截事件，利用全局路由导航守卫之前置导航钩子函数
router.beforeEach((to, from, next) => {
    //一、看访问地址是否为登录，如果是就next
  if(to.path=='/login'){
    next();
    return;
  }
  //二、是否存在登录信息（通过检查是否含有离线存储）
  if(store.state.userinfo){
    next();
    return;
  }
   //三、以上条件都不符合 强制它跳转到登录页
  next('/login')
})

export default router
